"""Background scheduler for periodic tasks."""

from __future__ import annotations

import logging
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

from .db.sync_session import get_sync_db
from .services.reminder_scheduler_service import ReminderSchedulerService
from .services.email_service import EmailService

logger = logging.getLogger(__name__)


def check_and_send_reminders_job() -> None:
    """
    定时任务：检查并发送跟进提醒.

    执行频率：每小时的第0分钟
    功能：
    1. 查询所有到期且未发送的提醒（reminder_time <= now, status=pending）
    2. 逐个发送邮件通知
    3. 更新提醒状态为sent
    """
    logger.info("Starting scheduled reminder check...")

    db = next(get_sync_db())
    try:
        email_service = EmailService()
        scheduler_service = ReminderSchedulerService(db, email_service)

        result = scheduler_service.check_and_send_reminders()

        logger.info(
            f"Reminder check completed: "
            f"total={result['total']}, "
            f"success={result['success']}, "
            f"failed={result['failed']}"
        )
    except Exception as e:
        logger.error(f"Reminder check failed: {type(e).__name__} - {str(e)}")
    finally:
        db.close()


def start_scheduler() -> BackgroundScheduler:
    """
    启动后台定时任务调度器.

    Returns:
        BackgroundScheduler: 调度器实例

    任务列表：
    - check_and_send_reminders: 每小时的第0分钟执行
    """
    scheduler = BackgroundScheduler(timezone="Asia/Shanghai")

    # 任务1：每小时检查跟进提醒
    scheduler.add_job(
        check_and_send_reminders_job,
        CronTrigger(minute=0),  # 每小时的第0分钟执行
        id="reminder_check",
        name="Check and send follow-up reminders",
        replace_existing=True,
        max_instances=1,  # 防止并发执行
    )

    scheduler.start()
    logger.info("Scheduler started successfully")
    logger.info("Scheduled jobs:")
    logger.info("  - reminder_check: Runs every hour at minute 0")

    return scheduler
